package com.boot.dao;

import org.postgresql.jdbc3.Jdbc3PoolingDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by xudi on 2/9/16.
 */
@Repository
public class JdbcTemplate {

    @Autowired
    Jdbc3PoolingDataSource dataSource;

    protected Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public Object execute(StatementCallback action) {
        Connection conn = null;
        Statement st=null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            st=conn.createStatement();
            Object object=action.doInStatement(st);
            return object;
        } catch (SQLException err) {
            err.printStackTrace();
            free(rs, st, conn);
        }finally{
            free(rs, st, conn);
        }
        return null;
    }

    protected void free(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
